package com.junmo.common.oss.config;

import com.junmo.common.oss.properties.MinioProperty;
import com.junmo.common.oss.service.OSSService;
import com.junmo.common.oss.serviceImpl.OSSServiceMinioImpl;
import com.junmo.common.util.StringUtils;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Configuration
@EnableConfigurationProperties(value = MinioProperty.class)
public class MinioConfig {

    @Autowired
    private MinioProperty minioProperty;

    @Bean
    public MinioClient minioClient() {
        return MinioClient.builder()
                .endpoint(minioProperty.getEndpoint(), minioProperty.getPort(), minioProperty.isSecure())
                .credentials(minioProperty.getAccessKey(), minioProperty.getSecretKey())
                .build();
    }

    @Bean
    public OSSService oosService(MinioClient minioClient) {
        log.info(">>>>>>>> minio config inited......");
        log.info(">>>> endpoint=" + minioProperty.getEndpoint() + ",Port=" + minioProperty.getPort() + ",sdkType=" + minioProperty.getSdkType());
        return new OSSServiceMinioImpl(minioProperty.getBucket(), minioClient, buildDataKeyValue());

    }

    /**
     * 用于对接数据中心amazon s3的copyObject、putObject接口，key、value由数据中心提供，可缺省
     *
     * @return
     */
    public Map<String, String> buildDataKeyValue() {
        if (StringUtils.isBlank(minioProperty.getDataKey()) || StringUtils.isBlank(minioProperty.getDataKeyValue())) {
            return null;
        }
        Map<String, String> map = new HashMap<>();
        map.put(minioProperty.getDataKeyValue(), minioProperty.getDataKey());
        return map;
    }
}
